/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2021-01-09
*/
package com.rzico.basics.service;

import com.rzico.base.BaseMapper;
import com.rzico.base.CommResult;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Chef;
import com.rzico.basics.entity.ChefLaud;
import com.rzico.basics.entity.Member;
import com.rzico.basics.mapper.ChefMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.basics.mapper.ChefLaudMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 笔记点赞业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class ChefLaudService extends BaseServiceImpl<ChefLaud, String> {

    @Autowired
    private ChefLaudMapper chefLaudMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ChefMapper chefMapper;

    @Override
    public BaseMapper<ChefLaud, String> getMapper() {
        return chefLaudMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public ChefLaud save(ChefLaud chefLaud) {
        int affectCount = 0;
        Member member = memberService.getCurrent();
        chefLaud.setMemberId(member.getId());
        chefLaud.setNickname(member.getUsername());
        chefLaud.setAvatar(member.getAvatar());
        //根据memberId和chefId查询出是否有这条点赞记录
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", member.getId());
        params.put("chefId", chefLaud.getChefId());
        List<ChefLaud> chefLauds = chefLaudMapper.selectList(params);
        if (chefLauds != null && chefLauds.size() > 0) {
            //点赞过的情况
            return null;
        } else {
            chefLaud.setCreateDate(new Date());
            affectCount = chefLaudMapper.insertUseGeneratedKeys(chefLaud);
        }

        if (affectCount <= 0) {
            return null;
        }
        //厨师表的厨师点赞还要+1
        params.put("id", chefLaud.getChefId());
        List<Chef> chefs = chefMapper.selectList(params);
        if (chefLauds != null && affectCount > 0) {
            Chef chef = chefs.get(0);
            if (chef.getLove() == null || chef.getLove() <= 0) {
                chef.setLove(0);
            }else {
                chef.setLove(chef.getLove() + 1);
            }
            chefMapper.updateByPrimaryKey(chef);
        }
        return chefLaud;
    }
}
